package com.focusai.efairy.ui.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.focusai.efairy.R;

import java.lang.ref.SoftReference;


public class CropView extends FrameLayout {
    private ImageView bgImgv;
    private RelativeLayout centerBgRltlyt;    //相框底层
    private RelativeLayout centerFrontRltlyt2;    //相框上层
    private TextView cancelTxv;
    private TextView confirmTxv;
    //	private final int FRAME_BORDER = 1; // 相框宽度 //TODO 可在引用xml文件里共同的资源
    private int bmWidth;    //图片宽度
    private int bmHeight;
    private int mFrameWidth;    //相框宽度
    private int mFrameHeight;

    private OnCropButtonClickListener mListener;
//	private MulitPointTouchListener mTouchListener;

    public CropView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
        setEvent();
    }

    private void initView() {
        View view = LayoutInflater.from(this.getContext()).inflate(
                R.layout.view_crop, this);
        bgImgv = (ImageView) view.findViewById(R.id.target_imageView);
        centerBgRltlyt = (RelativeLayout) view.findViewById(R.id.center_bg_rltlyt);
        centerFrontRltlyt2 = (RelativeLayout) view.findViewById(R.id.center_front_rltlyt);
        cancelTxv = (TextView) view.findViewById(R.id.crop_cancel_txv);
        confirmTxv = (TextView) view.findViewById(R.id.crop_confirm_txv);
    }

    public void setFrameSize(int width, int height) {
        this.mFrameWidth = width;
        this.mFrameHeight = height;

        setCenterSize();
    }

    private void setCenterSize() {
        android.widget.LinearLayout.LayoutParams lp = new android.widget.LinearLayout.LayoutParams(
                this.mFrameWidth, this.mFrameHeight);
        centerBgRltlyt.setLayoutParams(lp);
        android.widget.LinearLayout.LayoutParams lp2 = new android.widget.LinearLayout.LayoutParams(
                this.mFrameWidth, this.mFrameHeight);
        centerFrontRltlyt2.setLayoutParams(lp2);
    }

    public void setImage(SoftReference<Bitmap> bitmap, int srcWidth, int srcHeight) {
        if (bitmap != null && bitmap.get() != null && !bitmap.get().isRecycled()) {
            if (bgImgv == null) {
                initView();
                setCenterSize();
            }
            bmWidth = srcWidth;
            bmHeight = srcHeight;
            bgImgv.setImageBitmap(bitmap.get());
            requestLayout();
        }
    }

    private void setEvent() {
        cancelTxv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onCancel();
                }
            }
        });
        confirmTxv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onConfirm();
                }
            }
        });
    }

    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();
    float minScaleR;// 最小缩放比例
    static final float MAX_SCALE = 4f;// 最大缩放比例
    static final int NONE = 0;// 初始状态
    static final int DRAG = 1;// 拖动
    static final int ZOOM = 2;// 缩放
    int mode = NONE;
    PointF prev = new PointF();
    PointF mid = new PointF();
    float dist = 1f;


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            // 主点按下
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                prev.set(event.getX(), event.getY());
                mode = DRAG;
                break;
            // 副点按下
            case MotionEvent.ACTION_POINTER_DOWN:
                dist = spacing(event);
                // 如果连续两点距离大于10，则判定为多点模式
                if (spacing(event) > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    matrix.postTranslate(event.getX() - prev.x, event.getY()
                            - prev.y);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        float tScale = newDist / dist;
                        matrix.postScale(tScale, tScale, mid.x, mid.y);
                    }
                }
                break;
        }
        bgImgv.setImageMatrix(matrix);
        return true;
    }

    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

//		setCenterSize(Math.min(widthSize, heightSize));

        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
//		// 初始化图片位置和缩放
        initImagePlace();
    }

    private void initImagePlace() {
        if (this.bmWidth == 0) return;
        // 初始缩放
        int view_w = getResources().getDisplayMetrics().widthPixels;
        int view_h = this.getHeight();

        float scale = 1f;

        float scale_w = view_w / (float) bmWidth;
        float scale_h = view_w / (float) bmHeight;
        scale = scale_w > scale_h ? scale_w : scale_h;
        if (scale == 0) {
            scale = 1f;
        }

        Matrix matrix0 = new Matrix();
        matrix0.setScale(scale, scale);
        matrix0.postTranslate((view_w - bmHeight * scale) / 2, (view_h - bmWidth * scale) / 2);
        // 对监听缩放的matrix赋初始值
        matrix.set(matrix0);
//		mTouchListener.initMatrix(matrix0);
        bgImgv.setImageMatrix(matrix0);
    }

    public Bitmap getClipImage(Activity activity) {
        int barHeight = getBarHeight(activity);
        int frameBorder = getResources().getDimensionPixelSize(R.dimen.frame_border);

        Matrix matrix = new Matrix();
        matrix.setScale(600.0f / (centerBgRltlyt.getWidth() - 2 * frameBorder), 600.0f / (centerBgRltlyt.getHeight() - 2 * frameBorder));

        return Bitmap.createBitmap(
                takeScreenShot(activity),
                frameBorder,
                barHeight + getTop() + centerBgRltlyt.getTop() + frameBorder,
                centerBgRltlyt.getWidth() - 2 * frameBorder,
                centerBgRltlyt.getHeight() - 2 * frameBorder, matrix, true);


    }

    /**
     * @param activity
     * @param scaleWidth  图片需要被显示时的宽度
     * @param scaleHeight
     * @return
     */
    public Bitmap getCropImage(Activity activity, float scaleWidth, float scaleHeight) {
        int barHeight = getBarHeight(activity);
        int frameBorder = getResources().getDimensionPixelSize(R.dimen.frame_border);

        int clip_w = centerBgRltlyt.getWidth() - 2 * frameBorder;
        int clip_h = centerBgRltlyt.getHeight() - 2 * frameBorder;


        Matrix matrix = new Matrix();
        matrix.setScale(scaleWidth / clip_w, scaleHeight / clip_h);

        return Bitmap.createBitmap(
                takeScreenShot(activity),
                frameBorder,
                barHeight + getTop() + centerBgRltlyt.getTop() + frameBorder,
                clip_w,
                clip_h, matrix, true);
    }

    private Bitmap takeScreenShot(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        return view.getDrawingCache();

    }

    private int getBarHeight(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

    public void releaseBitmap() {
        this.bgImgv.setImageBitmap(null);
        this.bgImgv = null;
    }

    public void setOnCropButtonClickListener(OnCropButtonClickListener listener) {
        this.mListener = listener;
    }

    public interface OnCropButtonClickListener {

        public void onCancel();

        public void onConfirm();
    }
}
